<?php

/**
 * Created by PhpStorm.
 * User: boye003
 * Date: 2016/8/5
 * Time: 8:49
 */
namespace Admin\Controller;
use Uclient\Api\UserApi;
use Admin\Api\MemberApi;
use Admin\Api\AuthGroupAccessApi;
use Recruit\Api\UcenterMemberApi;
use Recruit\Api\UserResumeApi;


class SchoolController extends AdminController
{

    public function add_student($username = '', $password = '', $repassword = '',$nickname='',$sex='', $email = '')
    {
        if (IS_POST) {
            if ($password != $repassword) {
                $this->error("密码和重复密码不一致！");
            }
            //开启事务
            $modal = M();
            $modal -> startTrans();
            $flag = false;
            $result = apiCall(UserApi::REGISTER, array($username, $password, $email));
            $uid=$result['info'];
            if($result['status']){ //注册成功
                $entity = array(
                    'uid'=>$uid,
                    'nickname'=>$nickname,
                    'realname'=>$nickname,
                    'sex'=>$sex,
                    'idnumber'=>'',
                    'add_uid'=>UID//添加这个账号信息的用户id
                );

                $result = apiCall(MemberApi::ADD, array($entity));
                if(!$result['status']){
                    $flag = true;
                } else {
                    //插入到第三张表
                    $ent['group_id'] = C('USER_GROUNP_ID')['student'];
                    $result = apiCall(AuthGroupAccessApi::ADD_TO_GROUP,array($uid,$ent));
                    if(!$result['status']){
                        $flag = true;
                    }
                }
            }else { //注册失败，显示错误信息
                $flag = true;
            }
            if($flag){
                $modal -> rollback();
                $this->error('学生添加失败！');
            }else{
                $modal->commit();
                $this->success('学生添加成功！',U('School/add_student'));
            }
        }else{
          $this->display();
        }
    }


    /*
     * 学生信息的编辑 和接受存储
     * */
    public function edit_student(){
        if(IS_POST){
            //开启事务
            $modal = M();
            $modal -> startTrans();
            $flag = false;
            $entity['email'] = I('email');
            $result = apiCall(UserApi::SAVE_BY_ID, array(I('id'),$entity));
            if($result['status']){
                $membermap['uid'] = I('id');
                $membersave = array(
                    'nickname'=>I('nickname'),
                    'realname'=>I('nickname'),
                    'sex'=>I('sex'),
                );
                $result = apiCall(MemberApi::SAVE_BY_ID, array($membermap['uid'],$membersave));
                if(!$result['status']){
                    $flag = true;
                }
            }else{
                $flag = true;
            }
            if($flag){
                $modal -> rollback();
                $this->error('修改失败！');
            }else{
                $modal->commit();
                $this->success('修改成功！',U('Person/center'));
            }

        }else{
            $map['itboye_ucenter_member.id'] = I('id');
            $fields ='itboye_ucenter_member.id,itboye_ucenter_member.username,itboye_ucenter_member.email,common_member.nickname,common_member.sex';
            $info = apiCall(UcenterMemberApi::JOIN_AUTH_GET,array($map,'last_login_time desc',$fields));
            if($info['status']){
                $this->assign($info['info']);
            }
            $this->display();
        }
    }
    /*
         * 添加学生简历
         * */
    public function add_resume(){
        if(IS_POST){
            $entity = array(
                'uid' => I('uid'),
                'create_time' => time(),
                'update_time' => time(),
                'title' => I('title'),
                'content' => I('content'),
            );
            $result = apiCall(UserResumeApi::ADD,array($entity));
            if($result['status']){
                $this->success('简历添加成功',U('School/student_manager'));
            }else{
                $this->error('添加失败');
            }
        }else{
            $uid = I('id');
            $name = I('name');
            $this->assign('name',$name);
            $this->assign('uid',$uid);
            $this->display();
        }
    }

    /*
     * 编辑简历
     * */
    public function edit_resume(){
        if(IS_POST){
            $map['uid'] = I('uid');
            $entity = array(
                'update_time' => time(),
                'title' => I('title'),
                'content' => I('content'),
            );
            $info = apiCall(UserResumeApi::SAVE,array($map,$entity));
            if($info['status']){
                $this->success('修改成功',U('School/student_manager'));
            }else{
                $this->error('修改失败');
            }
        }else{
            $map['uid'] = I('id');
            $info = apiCall(UserResumeApi::GET_INFO,array($map));
            if($info['status']){
                $info['info']['content'] = htmlspecialchars_decode($info['info']['content']);
                $this->assign($info['info']);
            }
            $this->display();
        }
    }

    /*
     * 查询根据学生姓名
     * */
    public function search_student(){
        $nickname = I('nickname');
        $this->assign('nickname',$nickname);
        $map['nickname'] = array('like','%'.$nickname.'%');
        $map['group_id'] = C('USER_GROUNP_ID')['student'];
        $map['itboye_ucenter_member.status'] = 1;
        $map['add_uid'] = UID;
        $page = array('curpage'=>0,'size'=>10);
        $fields ='itboye_ucenter_member.id,itboye_ucenter_member.reg_time,itboye_ucenter_member.email,common_member.nickname';
        $info = apiCall(UcenterMemberApi::JOIN_AUTH_PAGE,array($map,$page,'reg_time desc',$map,$fields));
        if($info['status']){

            $this->assign('list',$info['info']['list']);
            $this->assign('show',$info['info']['show']);
        }
        $this->display();
    }

    /*
     * 学生信息列表
     * */
    public function student_manager(){
        $map['group_id'] = C('USER_GROUNP_ID')['student'];
        $map['itboye_ucenter_member.status'] = 1;
        $map['add_uid'] = UID;
        $page = array('curpage'=>0,'size'=>10);
        $fields ='itboye_ucenter_member.id,itboye_ucenter_member.reg_time,itboye_ucenter_member.email,common_member.nickname,itboye_user_resume.id as rid';
        $info = apiCall(UcenterMemberApi::JOIN_AUTH_PAGE,array($map,$page,'reg_time desc',$map,$fields));
        if($info['status']){
            $this->assign('list',$info['info']['list']);
            $this->assign('show',$info['info']['show']);
        }
        $this->display();

    }
    /*
     * AJAX假 删除学生
     * */
    public function ban_student(){
        $map['id'] = I('id');
        $entity['status'] = -1;
        $result = apiCall(UcenterMemberApi::SAVE,array($map,$entity));
        if($result['status']){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }

    }


    /**
     * 检测用户名是否已存在
     */
    public function check_username($username){
        $result = apiCall(UserApi::CHECK_USER_NAME,array($username));
        if($result['status']){
            echo "true";
        }else{
            echo "false";
        }
    }


    public function check_email($email){
        $result = apiCall(UserApi::CHECK_EMAIL,array($email));
        if($result['status']){
            echo "true";
        }else{
            echo "false";
        }
    }

    /**
     * 启用
     */
    public function enable(){
        parent::enable("uid");
    }
    /**
     * 禁用
     */
    public function disable(){
        if(is_administrator(I('uid',0))){
            $this->error("禁止对超级管理员进行禁用操作！");
        }
        parent::disable("uid");
    }

    public function delete(){
        if(is_administrator(I('uid',0))){
            $this->error("禁止对超级管理员进行删除操作！");
        }
        parent::pretendDelete("uid");
    }

    public function view(){
        $id = I('get.id',0);

        $result = apiCall(MemberApi::GET_INFO, array(array("uid"=>$id)));
        if(!$result['status']){
            $this->error($result['info']);
        }

        $this->assign("userinfo",$result['info']);

        $result = apiCall(UserApi::GET_INFO, array($id));

        if(!$result['status']){
            $this->error($result['info']);
        }

        $this->assign("useraccount",$result['info']);

        $result = apiCall(AuthGroupAccessApi::QUERY_GROUP_INFO, array($id));
        if(!$result['status']){
            $this->error($result['info']);
        }

        $this->assign("userroles",$result['info']);
        $this->display();
    }

    /*
     * 批量添加学生
     * */
    public function batch_student(){
        $path = './Uploads/Excel/student';

        if(is_dir($path))
        {
            if ($dh = opendir($path))
            {
                while (($file = readdir($dh)) !== false)
                {
                    if($file!="." && $file!="..")
                    {
                        $student[] = $file;
                    }
                }
                closedir($dh);
            }
        }
        $this->assign('student',$student);
        $this->display();
    }
    /*
     * 批量添加学生简历
     * */
    public function batch_resume(){

        $this->display();
    }

    /*
     * 图片Ajax上传
     * */
    public function upload(){
        //获取一个参数确定上传到哪个文件夹
        $path = I('get.type');

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload -> autoSub = false;//自动子目录保存文件
        $upload->exts      =     array('xls', 'xlsx');// 设置附件上传类型
        $upload->rootPath  =     './Uploads/Excel/'.$path.'/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        $upload->saveName  =     '';//控制上传文件保持原有名称
        // 上传文件
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            echo false;
        }else{// 上传成功
            echo $upload->saveName;
        }
    }

    /*
     * 学生导入数据库
     * */
    public function lead_student(){
        $filename = I('name');
        import("Org.Util.charset");//中文转拼音
        $charset = new \charset();
        $excelpath='./Uploads/Excel/student/'.$filename;
        import("Org.Util.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        $type = strrchr($filename,'.');
        if($type == '.xls'){
            import("Org.Util.PHPExcel.Reader.Excel5");
            $PHPReader=new \PHPExcel_Reader_Excel5();
        }else if($type == '.xlsx'){
            import("Org.Util.PHPExcel.Reader.Excel2007");
            $PHPReader=new \PHPExcel_Reader_Excel2007();
        }else{
            echo "<div>请选择正确的类型</div>";
            die();
        }
        $PHPExcel=$PHPReader->load($excelpath);
        $currentSheet=$PHPExcel->getSheet(0);
        //$allColumn=$currentSheet->getHighestColumn();取得列数
        $allRow=$currentSheet->getHighestRow();
        if($currentSheet->getCell('A1')->getValue() != '真实姓名' || $currentSheet->getCell('B1')->getValue() != '学号' || $currentSheet->getCell('C1')->getValue() != '身份证号码' || $currentSheet->getCell('D1')->getValue() != '性别' || $currentSheet->getCell('E1')->getValue() != '邮箱' || $currentSheet->getCell('F1')->getValue() != 'qq' || $currentSheet->getCell('G1')->getValue() != '密码'){
            echo '<div>请确认上传excel表格格式严格正确</div>';
            die();
        }

        $itboye_ucenter_member = M('ucenter_member');
        $common_member = M('member','common_');
        for($currentRow=2;$currentRow<=$allRow;$currentRow++){
            $m = M();
            $m->startTrans();
            $falg = false;
            $common_data['realname'] = $currentSheet->getCell("A".$currentRow)->getValue();
            $number = $currentSheet->getCell("B".$currentRow)->getValue();
            $common_data['nickname'] = iconv('gbk','utf-8//IGNORE',strtoupper($charset->PinYin(mb_convert_encoding($common_data['realname'] ,'gbk','utf-8')))).$number;
            //查找注册的学生是否已经存在获得冲突
            $usermap['username'] = $common_data['nickname'];
            $findres = apiCall(UserApi::FIND,array($usermap));
            if($findres['status']){
                if(is_null($findres['info'])) {
                    $common_data['idnumber'] = $currentSheet->getCell("C".$currentRow)->getValue();
                    if($currentSheet->getCell("D".$currentRow)->getValue() == '男'){
                        $common_data['sex'] = 1;
                    }else{
                        $common_data['sex'] = 0;
                    }
                    $common_data['qq'] = $currentSheet->getCell("F".$currentRow)->getValue();
                    $itboye_data['email'] = $currentSheet->getCell("E".$currentRow)->getValue();
                    $itboye_data['username'] = iconv('gbk','utf-8//IGNORE',strtoupper($charset->PinYin(mb_convert_encoding($common_data['realname'] ,'gbk','utf-8')))).$number;
                    $password = md5($currentSheet->getCell("G".$currentRow)->getValue());
                    $itboye_data['password'] = $password ? $password : md5('123456');//如果没有给密码默认123456
                    $itboye_data['reg_time'] = time();
                    $itboye_data['update_time'] = time();
                    $itboye_data['status'] = 1;
                    $itboye_data['reg_ip'] = $_SERVER['REMOTE_ADDR'];
                    $itboye_res = $itboye_ucenter_member->add($itboye_data);
                    if($itboye_res != false){
                        $common_data['uid'] = $itboye_res;
                        $common_data['add_uid'] = UID;
                        $common_data['update_time'] = time();
                        $common_res = $common_member->add($common_data);

                        if($common_res != false){
                            $ent['group_id'] = C('USER_GROUNP_ID')['student'];
                            $result = apiCall(AuthGroupAccessApi::ADD_TO_GROUP,array($itboye_res,$ent));
                            if(!$result['status']){
                                $flag = true;
                            }
                        }else{
                            $falg = true;
                        }
                    }else{
                        $falg = true;
                    }
                    if($falg == true){
                        $tipinfo[] = array($common_data['realname'],'添加失败');
                        $m->rollback();
                    }else{
                        $m->commit();
                    }
                }else{
                    $tipinfo[] = array($common_data['realname'],'该用户已经注册过或者注册是存在冲突');
                }
            }

        }
        if(is_array($tipinfo)){
            $str = '<h5>其余的注册成功了除了一下这些学生</h5><table class="table table-bordered">';
            foreach($tipinfo as $vo){
                $str = $str."<tr><td>".$vo['0']."</td><td>".$vo['1']."</td></tr>";
            }
            $str = $str."</table>";
            echo $str;
        }else{
            echo '导入成功';
        }
    }

    /*
     * 批量上传简历
     * */
    public function lead_resume(){
        $filename = I('name');
        $excelpath='./Uploads/Excel/resume/'.$filename;
        import("Org.Util.PHPExcel");
        import("Org.Util.charset");//中文转拼音
        $charset = new \charset();
        $objPHPExcel = new \PHPExcel();
        $type = strrchr($filename,'.');
        if($type == '.xls'){
            import("Org.Util.PHPExcel.Reader.Excel5");
            $PHPReader=new \PHPExcel_Reader_Excel5();
        }else if($type == '.xlsx'){
            import("Org.Util.PHPExcel.Reader.Excel2007");
            $PHPReader=new \PHPExcel_Reader_Excel2007();
        }else{
            echo "<div>请选择正确的类型</div>";
            die();
        }
        $PHPExcel=$PHPReader->load($excelpath);
        $currentSheet=$PHPExcel->getSheet(0);
        $allColumn=$currentSheet->getHighestColumn();
        $allRow=$currentSheet->getHighestRow();
        if($currentSheet->getCell('A1')->getValue() != '学号' || $currentSheet->getCell('B1')->getValue() != '姓名' || $currentSheet->getCell('C1')->getValue() != '简历名称' || $currentSheet->getCell('D1')->getValue() != '简历内容'){
            echo '<div>请确认上传excel表格格式严格正确</div>';
            die();
        }

        for($currentRow=2;$currentRow<=$allRow;$currentRow++){
            $number = $currentSheet->getCell("A".$currentRow)->getValue();
            $name = $currentSheet->getCell("B".$currentRow)->getValue();

            //查询出已经注册的学生ID
            $map['username'] =  iconv('gbk','utf-8//IGNORE',strtoupper($charset->PinYin(mb_convert_encoding($name ,'gbk','utf-8')))).$number;
            $studentinfo = apiCall(UserApi::FIND,array($map));
            if($studentinfo['status'] || !empty($studentinfo['info']['id'])){
                $entity['uid'] = $studentinfo['info']['id'];
            }else{
                $tipinfo[] = array($name,'该学生并没有注册请先注册');
            }
            //先做查找防止该人的简历存在
            $findres = apiCall(UserResumeApi::GET_INFO,array($entity));
            if($findres['status']){
                if(is_null($findres['info'])){
                    $entity['title'] = $currentSheet->getCell("C".$currentRow)->getValue();
                    $entity['content'] = $currentSheet->getCell("D".$currentRow)->getValue();
                    $entity['create_time'] = time();
                    $entity['update_time'] = time();
                    $res = apiCall(UserResumeApi::ADD,array($entity));
                    if($res['status'] == false){
                        $tipinfo[] = array($name,'该生添加时候出现了错误');
                    }
                }else{
                    $tipinfo[] = array($name,'该姓名的简历已经存在');
                }
            }

        }
        if(is_array($tipinfo)){
            $str = '<h5>其余的导入简历成功了除了一下这些学生</h5><table class="table table-bordered">';
            foreach($tipinfo as $vo){
                $str = $str."<tr><td>".$vo['0']."</td><td>".$vo['1']."</td></tr>";
            }
            $str = $str."</table>";
            echo $str;
        }else{
            echo '导入成功';
        }

    }

}